package com.mcy.springbatch.job;

import com.mcy.springbatch.entity.SysUser;
import com.mcy.springbatch.job.BaseJobConfig;
import com.mcy.springbatch.processer.SysUserItemProcessor;
import com.mcy.springbatch.writer.SysUserItemWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * 利用CompositeItemProcessor绑定多个Processor
 * @author : Create By mcy
 * @date : 2019/8/25 23:08:51
 */
@Slf4j
@Configuration
public class PMultiProcessorJobConfig extends BaseJobConfig {

    @Autowired
    ItemReader userDataListItemReader;

    @Autowired
    SysUserItemWriter sysUserItemWriter;

    @Bean
    public Job multiProcessorJob() {
        return jobBuilderFactory.get("multiProcessorJob")
                .incrementer(new RunIdIncrementer())
                .start(multiProcessorJobStep2())
                .build();
    }

    @Bean
    public Step multiProcessorJobStep2() {
        return stepBuilderFactory.get("multiProcessorJobStep2")
                .<SysUser, SysUser>chunk(2)
                .reader(userDataListItemReader)
                .processor(compositeItemProcessor())//多个process处理
                .writer(sysUserItemWriter)
                .build();
    }


    @Bean
    public CompositeItemProcessor<SysUser, SysUser> compositeItemProcessor() {
        return new CompositeItemProcessor() {{
            setDelegates(Arrays.asList(upperProcessor(), changeProcessor()));
        }};
    }

    @Bean
    public ItemProcessor<SysUser, SysUser> upperProcessor() {
        return item -> {
            item.setLoginName(item.getLoginName().toUpperCase());
            return item;
        };
    }

    @Bean
    public ItemProcessor<SysUser, SysUser> changeProcessor() {
        return item -> {
            if(item.getSex().equals("女")){
                item.setSex("保密");
            }
            return item;
        };
    }

}
